/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.api.runtime.process.operator;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.je.bpm.api.runtime.process.impl.APIProcessModelConverter;
import com.je.bpm.api.runtime.process.operator.desc.ProcessModelSaveParamDesc;
import com.je.bpm.api.runtime.process.operator.validator.ProcessModelSaveOperatorValidator;
import com.je.bpm.common.operation.OperatorEnum;
import com.je.bpm.core.json.converter.json.converter.BpmnJsonConverter;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.RepositoryService;
import com.je.bpm.engine.repository.Model;
import com.je.bpm.model.process.payloads.SaveOrUpdateProcessModelPayload;
import com.je.bpm.model.process.results.ProcessModelResult;
import com.je.bpm.runtime.process.operator.ProcessModelSaveOperator;
import com.je.bpm.runtime.shared.operator.AbstractOperator;
import com.je.bpm.runtime.shared.operator.desc.OperationParamDesc;
import com.je.bpm.runtime.shared.operator.validator.OperatorPayloadParamsValidator;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map;

/**
 * 保存流程模型
 */
public class ProcessModelSaveOrUpdateOperatorImpl extends AbstractOperator<SaveOrUpdateProcessModelPayload, ProcessModelResult> implements ProcessModelSaveOperator {

    private OperatorPayloadParamsValidator<SaveOrUpdateProcessModelPayload> validator = new ProcessModelSaveOperatorValidator();
    private APIProcessModelConverter apiProcessModelConverter;
    private RepositoryService repositoryService;

    public ProcessModelSaveOrUpdateOperatorImpl(APIProcessModelConverter apiProcessModelConverter, RepositoryService repositoryService) {
        this.apiProcessModelConverter = apiProcessModelConverter;
        this.repositoryService = repositoryService;
    }

    @Override
    public OperatorPayloadParamsValidator<SaveOrUpdateProcessModelPayload> getValidator() {
        return validator;
    }

    @Override
    public String getId() {
        return OperatorEnum.PROCESS_MODEL_SAVE_OPERATOR.getId();
    }

    @Override
    public String getName() {
        return OperatorEnum.PROCESS_MODEL_SAVE_OPERATOR.getName();
    }

    @Override
    public OperationParamDesc getParamDesc() {
        return new ProcessModelSaveParamDesc();
    }

    @Override
    public SaveOrUpdateProcessModelPayload paramsParse(Map<String, Object> params) {
        SaveOrUpdateProcessModelPayload payload = new SaveOrUpdateProcessModelPayload();
        payload.setModelId(params.get("modelId") == null ? null : params.get("modelId").toString());
        payload.setCategory(params.get("category") == null ? null : params.get("category").toString());
        payload.setFuncCode(params.get("funcCode") == null ? null : params.get("funcCode").toString());
        payload.setFuncName(params.get("funcName") == null ? null : params.get("funcName").toString());
        payload.setMetaInfo(params.get("metaInfo") == null ? null : params.get("metaInfo").toString());
        payload.setRunModeName(params.get("runModeName") == null ? null : params.get("runModeName").toString());
        payload.setRunModeCode(params.get("runModeCode") == null ? null : params.get("runModeCode").toString());
        payload.setDisabled(params.get("disabled") == null ? 0 : Integer.parseInt((String) params.get("disabled")));
        payload.setDeployStatus(params.get("deployStatus") == null ? 0 : Integer.parseInt((String) params.get("deployStatus")));
        return payload;
    }

    @Override
    public ProcessModelResult execute(SaveOrUpdateProcessModelPayload payload) {
        Model model = repositoryService.newModel();
        if (!Strings.isNullOrEmpty(payload.getModelId())) {
            model = repositoryService.getModel(payload.getModelId());
        }
        build(model, payload);
        repositoryService.saveModel(model);
        ProcessModelResult processModelResult = new ProcessModelResult(payload, apiProcessModelConverter.from(model));
        return processModelResult;
    }

    private void build(Model model, SaveOrUpdateProcessModelPayload payload) {
        try {
            model.setId(payload.getModelId());
            JsonNode modelNode = new ObjectMapper().readTree(new ByteArrayInputStream(payload.getMetaInfo().getBytes()));
            BpmnModel bpmnModel = new BpmnJsonConverter().convertToBpmnModel(modelNode);
            model.setName(bpmnModel.getMainProcess().getName());
            model.setKey(bpmnModel.getMainProcess().getId());
            //检查key是否重复
            checkRepeat(model.getId(), model.getKey());
            model.setCategory(payload.getCategory());
            model.setRunModeCode(payload.getRunModeCode());
            model.setRunModeName(payload.getRunModeName());
            model.setFuncCode(payload.getFuncCode());
            model.setFuncName(payload.getFuncName());
            model.setMetaInfo(payload.getMetaInfo());
            if(model.getDeployStatus()!=1){
                model.setDeployStatus(payload.getDeployStatus());
            }
            model.setDisabled(payload.getDisabled());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查model中的key是否重复
     *
     * @param modelId modelId，如果为空是创建，不为空是修改
     * @param key     model中的key
     * @return
     */
    private Boolean checkRepeat(String modelId, String key) {
        int modelCount = 0;
        if (Strings.isNullOrEmpty(modelId)) {
            if (repositoryService.createModelQuery().modelKey(key).list().size() > 0) {
                throw new ActivitiException("key重复，请检查！");
            }
        }

        if (!Strings.isNullOrEmpty(modelId)) {
            Model model = repositoryService.getModel(modelId);
            if (model == null) {
                throw new ActivitiException("model未找到，请检查！");
            }

            if (!model.getKey().equals(key)) {
                throw new ActivitiException("两次部署的modelKey不一致，请检查！");
            }
        }
        return true;
    }

}
